import { TableRef, db } from "@/api";
import { HeightUtil } from "@/util";
import { createAtom, useStore } from "@/util/hooks";
import { Input, Table, TableColumnProps } from "@arco-design/web-react";
import { RefInputType } from "@arco-design/web-react/es/Input";
import { RowCallbackProps } from "@arco-design/web-react/es/Table/interface";
import { IconSearch } from "@arco-design/web-react/icon";
import { useEffect, useRef } from "react";
import { DBTableAtom } from "..";
import { TableRefTableStore } from "./inteface";

export const TableRefTableAtom = createAtom<TableRefTableStore>({
  data: [],
});

export const TableRefTable = () => {
  const thisStore = useStore(TableRefTableAtom);
  const dbTableStore = useStore(DBTableAtom);
  const inputRef = useRef<RefInputType>(null);

  async function queryTableRefList() {
    const selectedRecord = dbTableStore.value.selected;
    if (selectedRecord) {
      const res = await db.tables(selectedRecord.id!);
      thisStore.updateStore({
        data: res.data,
        selectedRowKeys: [],
      });
    } else {
      thisStore.updateStore({
        data: [],
        selectedRowKeys: [],
      });
    }
  }

  function onRow(record: TableRef, index: number) {
    return {
      onClick(e) {
        thisStore.updateStoreAll((preValue) => {
          const newSelectOrUnSelect = record.tableName;
          const selectedRowKeys = [...(preValue.selectedRowKeys || [])];
          const index = selectedRowKeys.indexOf(newSelectOrUnSelect);
          if (index >= 0) {
            selectedRowKeys.splice(index, 1);
          } else {
            selectedRowKeys.push(newSelectOrUnSelect);
          }
          return {
            ...preValue,
            selectedRowKeys,
          };
        });
      },
    } as RowCallbackProps;
  }

  useEffect(() => {
    queryTableRefList();
  }, [dbTableStore.value.selected]);

  const columns: TableColumnProps[] = [
    {
      dataIndex: "tableName",
      title: "表名",
      filterIcon: <IconSearch />,
      filterDropdown: ({ filterKeys, setFilterKeys, confirm }) => (
        <div className="arco-table-custom-filter">
          <Input.Search
            ref={inputRef}
            searchButton
            placeholder="请输入"
            value={filterKeys?.[0] || ""}
            onChange={(value) => {
              setFilterKeys?.(value ? [value] : []);
            }}
            onSearch={() => {
              confirm?.();
            }}
          />
        </div>
      ),
      onFilter: (value, row) =>
        value ? row.tableName.indexOf(value) !== -1 : true,
      onFilterDropdownVisibleChange: (visible) => {
        if (visible) {
          setTimeout(() => inputRef.current!.focus(), 150);
        }
      },
    },
    {
      dataIndex: "tableComment",
      title: "注释",
    },
  ];

  return (
    <Table
      borderCell
      columns={columns}
      rowKey="tableName"
      data={thisStore.value.data}
      rowSelection={{
        preserveSelectedRowKeys: false,
        selectedRowKeys: thisStore.value.selectedRowKeys,
        // onChange被onRow包含
        onSelectAll(selected, selectedRows) {
          thisStore.updateStore({
            selectedRowKeys: selected
              ? selectedRows.map((k: TableRef) => k.tableName)
              : [],
          });
        },
      }}
      onRow={onRow}
      pagination={false}
      scroll={{
        y: HeightUtil.fillHeightStyle(2),
      }}
    />
  );
};
